# encoding: utf-8
from flask import Blueprint
from flask import request
from flask_api import status
from tools.camera.cgi_get_api import keyScan
import json
from tools.config import Config as config

CAMERAIP = config.IPC_CAMERA_IP
camera_action_control_bp = Blueprint('camera_action_control_bp', __name__)

def request_parse(request_data):
    ret_data = ""
    if request_data.method == "POST":
        ret_data = request_data.get_json()
    elif request_data.method == "GET":
        ret_data = json.loads(request_data.data.decode("utf8"))
    return ret_data

@camera_action_control_bp.route('/cameraControl', methods=['GET', 'POST'])
def cameraControl():
    global CAMERAIP
    ret_msg = 'ok', status.HTTP_200_OK
    data = request_parse(request)
    command_field = data.get("commandField")

    if isinstance(command_field, type(None)):
        return "command_field Can not be empty", status.HTTP_400_BAD_REQUEST
    commandSets = ['UP', 'DOWN', 'LEFT', 'RIGHT', 'CENTER']
    if not command_field.upper() in commandSets:
        return "commandType can only be ['UP', 'DOWN', 'LEFT', 'RIGHT', 'CENTER']", status.HTTP_400_BAD_REQUEST

    # 控制逻辑
    if command_field.upper() == commandSets[0]:
        keyScan(CAMERAIP, 'w')
    elif command_field.upper() == commandSets[1]:
        keyScan(CAMERAIP, 'x')
    elif command_field.upper() == commandSets[2]:
        keyScan(CAMERAIP, 'a')
    elif command_field.upper() == commandSets[3]:
        keyScan(CAMERAIP, 'd')
    elif command_field.upper() == commandSets[4]:
        keyScan(CAMERAIP, '5')  # 调用预设位， 居中

    return ret_msg
